const mongoose = require('mongoose')
const Address = require('./db/address')

// 连接数据库
mongoose.connect('mongodb://localhost:27017/xiaoyuanbang', {
  useNewUrlParser: true,
  useUnifiedTopology: true
})

// 测试地址数据
const testAddresses = [
  {
    id: 'addr_1',
    name: '张三',
    phone: '138****8888',
    fullAddress: '3号宿舍楼 301室',
    isDefault: true,
    userId: 'user123'
  },
  {
    id: 'addr_2',
    name: '李四',
    phone: '139****9999',
    fullAddress: '5号宿舍楼 502室',
    isDefault: false,
    userId: 'user123'
  },
  {
    id: 'addr_3',
    name: '王五',
    phone: '137****7777',
    fullAddress: '图书馆自习室',
    isDefault: false,
    userId: 'user123'
  }
]

// 初始化地址数据
async function initAddresses() {
  try {
    // 清空现有数据
    await Address.deleteMany({ userId: 'user123' })
    console.log('已清空现有地址数据')

    // 插入测试数据
    const result = await Address.insertMany(testAddresses)
    console.log(`成功插入 ${result.length} 条地址数据`)

    // 显示插入的数据
    const addresses = await Address.find({ userId: 'user123' })
    console.log('当前地址列表:')
    addresses.forEach(addr => {
      console.log(`- ${addr.name}: ${addr.fullAddress} (${addr.isDefault ? '默认' : '普通'})`)
    })

  } catch (error) {
    console.error('初始化地址数据失败:', error)
  } finally {
    // 关闭数据库连接
    mongoose.connection.close()
    console.log('数据库连接已关闭')
  }
}

// 运行初始化
initAddresses()

